<template>
  <div class="achievement-container">
    <div class="class-management-container">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
        >
          <van-swipe-cell v-for="item in classList.data" :key="item.classId">
            <van-cell
                :title="item.className"
                :label="`${item.grade} | ${item.major} | ${item.college}`"
            />
            <template #right>
              <van-button
                  square
                  type="primary"
                  text="编辑"
                  @click.stop="handleEdit(item)"
              />
              <van-button
                  square
                  type="danger"
                  text="删除"
                  @click.stop="handleDelete(item)"
              />
            </template>
          </van-swipe-cell>
        </van-list>
      </van-pull-refresh>

      <!-- 新增班级表单 -->
      <van-popup v-model:show="showAddForm" position="bottom" round :style="{ height: '50%' }">
        <van-nav-bar
            title="新增班级"
            left-text="取消"
            right-text="保存"
            @click-left="showAddForm = false"
            @click-right="handleAddClass"
        />
        <van-form class="form-container">
          <van-cell-group inset>
            <van-field
                v-model="newClass.className"
                label="班级名称"
                placeholder="请输入班级名称"
            />
            <van-field
                v-model="newClass.grade"
                label="年级"
                placeholder="请输入年级"
            />
            <van-field
                v-model="newClass.major"
                label="专业"
                placeholder="请输入专业"
            />
            <van-field
                v-model="newClass.college"
                label="学院"
                placeholder="请输入学院"
            />
          </van-cell-group>
        </van-form>
      </van-popup>

      <!-- 编辑班级表单 -->
      <van-popup v-model:show="showEditForm" position="bottom" round :style="{ height: '50%' }">
        <van-nav-bar
            title="编辑班级"
            left-text="取消"
            right-text="保存"
            @click-left="showEditForm = false"
            @click-right="handleEditSubmit"
        />
        <van-form class="form-container">
          <van-cell-group inset>
            <van-field
                v-model="editClass.className"
                label="班级名称"
                placeholder="请输入班级名称"
            />
            <van-field
                v-model="editClass.grade"
                label="年级"
                placeholder="请输入年级"
            />
            <van-field
                v-model="editClass.major"
                label="专业"
                placeholder="请输入专业"
            />
            <van-field
                v-model="editClass.college"
                label="学院"
                placeholder="请输入学院"
            />
          </van-cell-group>
        </van-form>
      </van-popup>

      <van-floating-bubble
          v-model:offset="offset"
          axis="xy"
          icon="plus"
          magnetic="x"
          @click="showAddForm = true"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {showConfirmDialog, showFailToast, showSuccessToast, showToast} from 'vant'
import { useUserStore } from '../../../Store/modules/userinfo/UserInfo'
import { useClassInfoStore } from '../../../Store/modules/ClassInfo'
import {
  addClassUsingPost,
  deleteClassUsingPost,
  updateClassUsingPost,
  listClassesByCounselorUsingGet
} from '../../../api/banjimokuai'

const userStore = useUserStore()
const classInfoStore = useClassInfoStore()

// 当前用户ID
const currentUserId = computed(() => userStore.userInfo?.userId || 0)

// 直接从Pinia获取班级列表
const classList = computed(() => classInfoStore.classInfoList)

// 列表相关状态
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const showAddForm = ref(false)
const showEditForm = ref(false)

// 新增班级表单数据
const newClass = ref({
  className: '',
  grade: '',
  major: '',
  college: '',
  counselorId: currentUserId.value
})

// 编辑班级表单数据
const editClass = ref({
  classId: 0,
  className: '',
  grade: '',
  major: '',
  college: '',
  counselorId: currentUserId.value
})

// 悬浮按钮位置
const offset = ref({ x: 315, y: 700 })

// 编辑班级
const handleEdit = (item) => {
  editClass.value = {
    classId: item.classId,
    className: item.className,
    grade: item.grade || '',
    major: item.major || '',
    college: item.college || '',
    counselorId: currentUserId.value
  }
  showEditForm.value = true
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    const response = await updateClassUsingPost(editClass.value)
    if (response.data.code === 0) {
      showSuccessToast('更新成功')
      showEditForm.value = false
      await fetchClassList()
    } else {
      showToast(response.message || '更新失败')
    }
  } catch (error) {
    showFailToast('更新失败')
    console.error('更新班级失败:', error)
  }
}

// 删除班级
const handleDelete = async (item) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除班级 ${item.className} 吗？`,
    })

    const res = await deleteClassUsingPost({
      classId: item.classId,
      counselorId: currentUserId.value
    })

    if (res.data.code === 0) {
      showSuccessToast('删除成功')
      await fetchClassList()
    } else {
      showFailToast(res.message || '删除失败')
    }
  } catch (error) {
    showFailToast(error.message || '删除失败')
    console.error('删除班级失败:', error)
  }
}

// 新增班级
const handleAddClass = async () => {
  try {
    const response = await addClassUsingPost(newClass.value)
    showSuccessToast('新增成功')
    showAddForm.value = false
    resetNewClassForm()
    await fetchClassList()
  } catch (error) {
    showFailToast('新增失败')
  }
}

// 重置新增表单
const resetNewClassForm = () => {
  newClass.value = {
    className: '',
    grade: '',
    major: '',
    college: '',
    counselorId: currentUserId.value
  }
}

// 获取班级列表
const fetchClassList = async () => {
  loading.value = true
  try {
    const response = await listClassesByCounselorUsingGet({
      counselorId: currentUserId.value
    })
    classInfoStore.classInfoList = response.data || []
  } catch (error) {
    console.error('获取班级列表失败:', error)
  } finally {
    loading.value = false
    refreshing.value = false
    finished.value = true
  }
}

// 下拉刷新
const onRefresh = () => {
  finished.value = false
  refreshing.value = true
  fetchClassList()
}

// 上拉加载
const onLoad = () => {
  fetchClassList()
}

// 初始化加载班级数据
onMounted(() => {
  fetchClassList()
})
</script>

<style scoped>
.achievement-container {
  height: 100vh;
  overflow-y: auto;
  padding: 10px;
}

.van-swipe-cell {
  margin-bottom: 1px;
}

:deep(.van-pull-refresh) {
  height: 100vh;
}

.form-container {
  padding: 16px;
}

/* 侧滑按钮样式 */
.van-swipe-cell__right {
  display: flex;
}

.van-button {
  height: 100%;
}

/* 编辑按钮 - 白色样式 */
:deep(.van-swipe-cell .van-button--primary) {
  background-color: #dcdcdc;
  color: #323233;
  border: none;
}

:deep(.van-swipe-cell .van-button--primary:active) {
  background-color: #f2f3f5;
}

/* 删除按钮 - 紫色样式 */
:deep(.van-swipe-cell .van-button--danger) {
  background-color: #9a009a;
  border: none;
}

:deep(.van-swipe-cell .van-button--danger:active) {
  background-color: #7c2d7c;
}

/* 悬浮按钮样式 */
:deep(.van-floating-bubble) {
  background-color: #9a009a;
  color: white;
}

:deep(.van-floating-bubble:active) {
  background-color: #7c2d7c;
}

/* 弹窗按钮样式 */
:deep(.van-popup .van-nav-bar__text) {
  color: #9a009a;
}

:deep(.van-popup .van-nav-bar__text:active) {
  color: #7c2d7c;
}
</style>
